package me.victor.jetpackcompose

import android.util.Log
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SwipeToDismissBox
import androidx.compose.material3.SwipeToDismissBoxValue
import androidx.compose.material3.Text
import androidx.compose.material3.rememberSwipeToDismissBoxState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.toMutableStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.launch

/**
 * @author song.zheng
 * @create 2024/6/6
 * @description 用derivedStateOf提升性能
 */
const val TAG = "Victor"

@Composable
fun MainLayout() {
    Log.d(TAG, "MainLayout Recomposed")
    var clickCount by remember { mutableStateOf(0) }

    Column {
        Button(onClick = { clickCount++ }) {
            Text(text = "Click me")
        }
        if (clickCount >= 5) {
            Text(text = "You clicked a lot")
        }
    }
}

@Composable
fun MainLayout2() {
    Log.d(TAG, "MainLayout Recomposed")
    var clickCount by remember { mutableStateOf(0) }
    val clickedALot by remember { derivedStateOf { clickCount >= 5 } }

    Column {
        Button(onClick = { clickCount++ }) {
            Text(text = "Click me")
        }
        if (clickedALot) {
            Text(text = "You clicked a lot")
        }
    }
}

@Composable
fun MainLayout3() {
    Log.d(TAG, "MainLayout Recomposed")
    val state = rememberLazyListState()

    Box(modifier = Modifier.fillMaxSize()) {
        ScrollableList(state)
        val shouldShowBackToTopButton = state.firstVisibleItemIndex != 0
        val coroutineScope = rememberCoroutineScope()
        BackToTopButton(shouldShowBackToTopButton) {
            coroutineScope.launch { state.animateScrollToItem(0) }
        }
    }
}

@Composable
fun MainLayout4() {
    Log.d(TAG, "MainLayout Recomposed")
    val state = rememberLazyListState()

    Box(modifier = Modifier.fillMaxSize()) {
        ScrollableList(state)
        val shouldShowBackToTopButton by remember {
            derivedStateOf { state.firstVisibleItemIndex != 0 }
        }
        val coroutineScope = rememberCoroutineScope()
        BackToTopButton(shouldShowBackToTopButton) {
            coroutineScope.launch { state.animateScrollToItem(0) }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
@Composable
fun ScrollableList(state: LazyListState) {
    val list = ('A'..'Z').map { it.toString() }.toMutableStateList()

    LazyColumn(state = state) {
        items(list, key = { it }) { letter ->
            val animatedProgress = remember { Animatable(initialValue = 300f) }
            LaunchedEffect(Unit) {
                Log.d(TAG, "LaunchedEffect")
                animatedProgress.animateTo(
                    targetValue = 0f,
                    animationSpec = tween(300, easing = FastOutSlowInEasing)
                )
            }
            DisposableEffect(Unit) {
                Log.d(TAG, "DisposableEffect")
                onDispose { Log.d(TAG, "onDispose") }
            }
            val dismissState = rememberSwipeToDismissBoxState(confirmValueChange = {
                if (it == SwipeToDismissBoxValue.EndToStart) {
                    list.remove(letter)
                    true
                } else {
                    false
                }
            }, positionalThreshold = {
                it / 2
            })
            SwipeToDismissBox(
                state = dismissState,
                backgroundContent = {
                    val color by animateColorAsState(
                        targetValue = when (dismissState.targetValue) {
                            SwipeToDismissBoxValue.Settled -> MaterialTheme.colorScheme.surface
                            SwipeToDismissBoxValue.StartToEnd -> Color.Green
                            SwipeToDismissBoxValue.EndToStart -> Color.Red
                        }
                    )
                    val scale by animateFloatAsState(targetValue =
                        if (dismissState.targetValue == SwipeToDismissBoxValue.Settled) {
                            0.75f
                        } else {
                            1f
                        }
                    )

                    Box(
                        modifier = Modifier
                            .fillMaxSize()
                            .background(color)
                            .padding(12.dp),
                        contentAlignment = Alignment.CenterEnd
                    ) {
                        Icon(
                            imageVector = Icons.Default.Delete,
                            contentDescription = null,
                            modifier = Modifier.scale(scale)
                        )
                    }
                },
                modifier = Modifier.animateItemPlacement(),
                enableDismissFromStartToEnd = false
            ) {
                Card(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(120.dp)
                        .padding(10.dp)
                        .clickable { list.remove(letter) }
                        .graphicsLayer(translationX = animatedProgress.value)
                ) {
                    Text(
                        text = letter,
                        textAlign = TextAlign.Center,
                        fontSize = 20.sp,
                        modifier = Modifier
                            .fillMaxSize()
                            .wrapContentHeight(Alignment.CenterVertically)
                    )
                }
            }
        }
    }
}

@Composable
fun BoxScope.BackToTopButton(isVisible: Boolean, onBackToTop: () -> Unit) {
    if (isVisible) {
        FloatingActionButton(
            onClick = onBackToTop,
            modifier = Modifier
                .align(Alignment.BottomEnd)
                .rotate(90f)
                .padding(20.dp),
            shape = CircleShape
        ) {
            Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back To Top")
        }
    }
}